import { useState, useCallback, useRef, useEffect } from 'react';
import { useTVEventHandler } from 'react-native';

export interface FocusableItem {
  id: string;
  x: number; // 列坐标
  y: number; // 行坐标
  onFocus?: () => void; // 聚焦时调用
  onPress?: () => void; // 点击OK键时调用
  canFocus?: boolean; // 是否可以聚焦
}

export interface FocusGridOptions {
  onFocusChange?: (item: FocusableItem | null) => void;
  wrapAround?: boolean; // 是否循环导航
  autoUpdate?: boolean; // 是否自动更新坐标
}

export const useFocusGrid = (options: FocusGridOptions = {}) => {
  const [focusedItem, setFocusedItem] = useState<FocusableItem | null>(null);
  const [focusedPosition, setFocusedPosition] = useState({ x: 0, y: 0 });
  const gridRef = useRef<FocusableItem[][]>([]);
  const { wrapAround = true, onFocusChange, autoUpdate = true } = options;

  // 动态计算坐标
  const calculateCoordinates = useCallback((items: FocusableItem[][]): FocusableItem[][] => {
    return items.map((row, y) => 
      row.map((item, x) => ({
        ...item,
        x,
        y,
      }))
    );
  }, []);

  // 注册焦点网格
  const registerGrid = useCallback((items: FocusableItem[][]) => {
    const gridWithCoords = calculateCoordinates(items);
    gridRef.current = gridWithCoords;
    
    // 设置初始焦点到第一个可聚焦的项目
    const firstFocusable = findFirstFocusable(gridWithCoords);
    if (firstFocusable) {
      setFocusedItem(firstFocusable);
      setFocusedPosition({ x: firstFocusable.x, y: firstFocusable.y });
      firstFocusable.onFocus?.();
      onFocusChange?.(firstFocusable);
    }
  }, [calculateCoordinates, onFocusChange]);

  // 更新网格（保持当前焦点）
  const updateGrid = useCallback((items: FocusableItem[][]) => {
    const gridWithCoords = calculateCoordinates(items);
    const oldGrid = gridRef.current;
    gridRef.current = gridWithCoords;
    
    // 尝试保持当前焦点
    if (focusedItem) {
      const newFocusedItem = findItemById(gridWithCoords, focusedItem.id);
      if (newFocusedItem) {
        setFocusedItem(newFocusedItem);
        setFocusedPosition({ x: newFocusedItem.x, y: newFocusedItem.y });
        newFocusedItem.onFocus?.();
        onFocusChange?.(newFocusedItem);
        return;
      }
    }
    
    // 如果当前焦点项目不存在，设置到第一个可聚焦项目
    const firstFocusable = findFirstFocusable(gridWithCoords);
    if (firstFocusable) {
      setFocusedItem(firstFocusable);
      setFocusedPosition({ x: firstFocusable.x, y: firstFocusable.y });
      firstFocusable.onFocus?.();
      onFocusChange?.(firstFocusable);
    }
  }, [calculateCoordinates, focusedItem, onFocusChange]);

  // 根据ID查找项目
  const findItemById = (grid: FocusableItem[][], id: string): FocusableItem | null => {
    for (let y = 0; y < grid.length; y++) {
      for (let x = 0; x < grid[y].length; x++) {
        const item = grid[y][x];
        if (item && item.id === id) {
          return item;
        }
      }
    }
    return null;
  };

  // 查找第一个可聚焦的项目
  const findFirstFocusable = (grid: FocusableItem[][]): FocusableItem | null => {
    for (let y = 0; y < grid.length; y++) {
      for (let x = 0; x < grid[y].length; x++) {
        const item = grid[y][x];
        if (item && item.canFocus !== false) {
          return item;
        }
      }
    }
    return null;
  }

  // 查找指定方向的下一个可聚焦项目
  const findNextFocusable = useCallback((direction: 'up' | 'down' | 'left' | 'right'): FocusableItem | null => {
    const grid = gridRef.current;
    const { x, y } = focusedPosition;
    
    let nextX = x;
    let nextY = y;
    
    switch (direction) {
      case 'up':
        nextY = wrapAround ? (y - 1 + grid.length) % grid.length : Math.max(0, y - 1);
        break;
      case 'down':
        nextY = wrapAround ? (y + 1) % grid.length : Math.min(grid.length - 1, y + 1);
        break;
      case 'left':
        nextX = wrapAround ? (x - 1 + grid[y].length) % grid[y].length : Math.max(0, x - 1);
        break;
      case 'right':
        nextX = wrapAround ? (x + 1) % grid[y].length : Math.min(grid[y].length - 1, x + 1);
        break;
    }

    // 检查目标位置是否有可聚焦的项目
    if (grid[nextY] && grid[nextY][nextX] && grid[nextY][nextX].canFocus !== false) {
      return grid[nextY][nextX];
    }
    
    return null;
  }, [focusedPosition, wrapAround]);

  // 导航到指定项目
  const focusItem = useCallback((item: FocusableItem) => {
    setFocusedItem(item);
    setFocusedPosition({ x: item.x, y: item.y });
    item.onFocus?.();
    onFocusChange?.(item);
  }, [onFocusChange]);

  // 导航逻辑
  const navigate = useCallback((direction: 'up' | 'down' | 'left' | 'right') => {
    const nextItem = findNextFocusable(direction);
    if (nextItem) {
      focusItem(nextItem);
    }
  }, [findNextFocusable, focusItem]);

  // 处理按键事件
  useTVEventHandler((evt: any) => {
    const { eventType } = evt;
    
    switch (eventType) {
      case 'up':
        navigate('up');
        break;
      case 'down':
        navigate('down');
        break;
      case 'left':
        navigate('left');
        break;
      case 'right':
        navigate('right');
        break;
      case 'select':
      case 'enter':
        focusedItem?.onPress?.();
        break;
    }
  });

  // 检查项目是否被聚焦
  const isFocused = useCallback((item: FocusableItem) => {
    return focusedItem?.id === item.id;
  }, [focusedItem]);

  // 获取当前焦点位置
  const getFocusedPosition = useCallback(() => focusedPosition, [focusedPosition]);

  return {
    focusedItem,
    focusedPosition,
    registerGrid,
    updateGrid,
    focusItem,
    navigate,
    isFocused,
    getFocusedPosition,
  };
}; 